package com.sunny.core.controller;

import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.miemiedev.mybatis.paginator.domain.Order;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sunny.core.bean.PersonInfo;
import com.sunny.core.bean.UserInfo;
import com.sunny.core.service.IPersonInfoService;
import com.sunny.core.service.IUserInfoService;
import com.sunny.core.utils.CommonResult;
import com.sunny.core.utils.CommonStringUtils;
import com.sunny.core.utils.Constant;

@Controller
@RequestMapping("/user")
public class UserController {
	
		@Resource(name = "userInfoService")
		private IUserInfoService userInfoService;

		@Resource(name = "personInfoService")
		private IPersonInfoService personInfoService;

		/**
		 *  用户查询
		 */
		@SuppressWarnings("unchecked")
		@RequestMapping(value = "/query", method = { RequestMethod.POST,
				RequestMethod.GET })
		public ModelAndView queryAll(HttpServletRequest request,
				HttpServletResponse response,Model m,UserInfo userInfo) throws Exception {

			String pageNum = request.getParameter("pageNum");
			String pageSize = request.getParameter("pageSize");
			System.out.println("pageNum" + pageNum);
			int num = 1;
			int size = 10;
			if (pageNum != null && !"".equals(pageNum)) {
				num = Integer.parseInt(pageNum);
			}
			if (pageSize != null && !"".equals(pageSize)) {
				size = Integer.parseInt(pageSize);
			}
			String sortString = "id.desc";
			Order.formString(sortString);

			PageHelper.startPage(num, size);
			
			String searchType = request.getParameter("searchType");
			String searchValue = request.getParameter("searchValue");
			
			if (StringUtils.isNotBlank(searchType)) {
				if (searchType.equals("1")) {
					userInfo.setRealName(searchValue);
				}
				if (searchType.equals("2")) {
					userInfo.setNickName(searchValue);
				}
				
			}
			
			List<UserInfo> userInfoList = userInfoService.query(userInfo);

			PageInfo<UserInfo> pagehelper = new PageInfo<UserInfo>(userInfoList);

			// 返回ModelAndView
			ModelAndView modelAndView = new ModelAndView();
			// 相当 于request的setAttribut，在jsp页面中通过personList取数据
			// modelAndView.addObject("personList", personList);
			modelAndView.addObject("pagehelper", pagehelper);

			m.addAttribute("userInfoList",userInfoList);
			m.addAttribute("total",pagehelper.getTotal());
			m.addAttribute("pageSize",pagehelper.getPageSize());
			m.addAttribute("pageNum",num);
//			System.out.println("------" + searchValue);
			m.addAttribute("searchType",searchType);
			m.addAttribute("searchValue",searchValue);
			
			
			// 指定视图
			// 下边的路径，如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀，修改为
			// modelAndView.setViewName("/jsp/personList.jsp");
			// 上边的路径配置可以不在程序中指定jsp路径的前缀和jsp路径的后缀
			modelAndView.setViewName("user/user_info_list");
			return modelAndView;

		}
		
		/**
		 * 用户登录
		 * @param request
		 * @param response
		 * @return
		 * @throws Exception
		 */
		@RequestMapping(value = "/login", method = { RequestMethod.POST,
				RequestMethod.GET })
		@ResponseBody
		public Map login(HttpServletRequest request,HttpSession session) throws Exception {
			
			UserInfo  s =null;
			
			Map<String, Object> map = new HashMap<String,Object>();
			
			map.put("status",1);
			map.put("msg","登录失败");
			
			String loginNameFromWeb = request.getParameter("loginName");
			String loginPasswordFromWeb = request.getParameter("loginPassword");
			
			UserInfo userInfo = userInfoService.selectByLoginName(loginNameFromWeb);
			
			if (userInfo != null) {
				//用户名和密码都相同,登录成功
				if (loginNameFromWeb != null && loginPasswordFromWeb.equals(userInfo.getLoginPassword())){
					map.put("status",0);
					map.put("msg","登录成功");
					
					session.setAttribute("currentUser", userInfo);
					
					
					
					
				} else {
					map.put("status",1);
					map.put("msg","密码错误");
				}
			} else if (loginNameFromWeb != null) {
				map.put("status",1);
				map.put("msg","用户名不存在");
			}
			
			return map;
		}
		/**
		 * 删除用户
		 * @param request
		 * @param response
		 * @return
		 * @throws Exception
		 */
		@RequestMapping(value = "/delete", method = { RequestMethod.POST,
				RequestMethod.GET })
		@ResponseBody
		public CommonResult delete(HttpServletRequest request,HttpSession session,UserInfo userInfo) throws Exception {	
			CommonResult commonResult = new CommonResult();
			String userPid = request.getParameter("userPid");
			userInfo.setUserPid(userPid);
			userInfo.setIsdel(1);
			int result = userInfoService.updateByPrimaryKeySelective(userInfo);
			if (result == 1) {
				commonResult.setStatus(Constant.RESULT_SCUSSES_CODE);
				commonResult.setMsg(Constant.RESULT_DELSUC_DESC);
			} else {
				commonResult.setStatus(Constant.RESULT_ERROR_CODE);
				commonResult.setMsg(Constant.RESULT_DELERR_DESC);
			}
			return commonResult;
		}

		/**
		 *  跳到用户新增页面
		 */
		@SuppressWarnings("unchecked")
		@RequestMapping(value = "/toAdd", method = { RequestMethod.POST,
				RequestMethod.GET })
		public ModelAndView toAdd(HttpServletRequest request,
				HttpServletResponse response,Model m) throws Exception {
			
			ModelAndView modelAndView = new ModelAndView();
			
			modelAndView.setViewName("user/user_info_crud");
			return modelAndView;

		}
		
		@RequestMapping(value = "/add", method = { RequestMethod.POST,
				RequestMethod.GET })
		@ResponseBody
		public CommonResult add(HttpServletRequest request,HttpSession session,UserInfo userInfo) throws Exception {	
			CommonResult commonResult = new CommonResult();
			
	        Enumeration<String> e = session.getAttributeNames();
	        while (e.hasMoreElements()) {
	            String s = e.nextElement();
//	            System.out.println(s + " == " + session.getAttribute(s));
	        }
			
			UserInfo currentUser = (UserInfo) session.getAttribute("currentUser");
			
			PersonInfo entity = new PersonInfo();
			entity.setPersonPid(userInfo.getPersonPid());//获得关联人员id
			PersonInfo personInfo = personInfoService.selectByPrimaryKey(entity);//根据关联人员id，查到person_info
			
			userInfo.setUserPid(CommonStringUtils.get32UUID());
			userInfo.setRealName(personInfo.getPersonName());//user的realname是person的name
			userInfo.setIsdel(new Integer(0));
			userInfo.setCreateTime(new Date());
			userInfo.setCreateUserid(currentUser.getUserPid());
			userInfo.setCreateUsername(currentUser.getRealName());//
			
			int result = userInfoService.save(userInfo);
			if (result == 1) {
				commonResult.setStatus(Constant.RESULT_SCUSSES_CODE);
				commonResult.setMsg(Constant.RESULT_ADDSUC_DESC);
			} else {
				commonResult.setStatus(Constant.RESULT_ERROR_CODE);
				commonResult.setMsg(Constant.RESULT_ADDERR_DESC);
			}
			return commonResult;
		}
		
		/**
		 *  跳到用户新增页面
		 */
		@SuppressWarnings("unchecked")
		@RequestMapping(value = "/toEdit", method = { RequestMethod.POST,
				RequestMethod.GET })
		public ModelAndView toEdit(HttpServletRequest request,
				HttpServletResponse response,Model m,UserInfo userInfo) throws Exception {

			ModelAndView modelAndView = new ModelAndView();
			
			if (userInfo != null && StringUtils.isNotBlank(userInfo.getUserPid())) {
				UserInfo entity = userInfoService.selectByPrimaryKey(userInfo);
				
				
				if (entity != null) {
					
					m.addAttribute("flag","edit");
					m.addAttribute("userInfo",entity);
					
					PersonInfo personInfo = null;
					List<PersonInfo> personInfoList = personInfoService.query(personInfo);
					m.addAttribute("personInfoList",personInfoList);
					
					modelAndView.setViewName("user/user_info_crud");
					return modelAndView;
				} else {
					return null;
				}
			}
			return null;
		}
		
		@RequestMapping(value = "/update", method = { RequestMethod.POST,
				RequestMethod.GET })
		@ResponseBody
		public CommonResult update(HttpServletRequest request,HttpSession session,UserInfo userInfo) throws Exception {	
			CommonResult commonResult = new CommonResult();
			
			commonResult.setStatus(Constant.RESULT_ERROR_CODE);
			commonResult.setMsg(Constant.RESULT_UPERR_DESC);
			
			if (userInfo != null && userInfo.getUserPid() != null) {
				userInfo.setUpdateTime(new Date());
				userInfo.setCreateTime(new Date());
				
				PersonInfo entity = new PersonInfo();
				entity.setPersonPid(userInfo.getPersonPid());//获得关联人员id
				PersonInfo personInfo = personInfoService.selectByPrimaryKey(entity);//根据关联人员id，查到person_info
				
				userInfo.setRealName(personInfo.getPersonName());//user的realname是person的name
				
				int result = userInfoService.updateByPrimaryKeySelective(userInfo);
				
				if (result == 1) {
					commonResult.setStatus(Constant.RESULT_SCUSSES_CODE);
					commonResult.setMsg(Constant.RESULT_UPSUC_DESC);
				} else {
					commonResult.setStatus(Constant.RESULT_ERROR_CODE);
					commonResult.setMsg(Constant.RESULT_UPERR_DESC);
				}
			}

			return commonResult;
		}

		/**
		 *  跳到用户详情页面
		 */
		@SuppressWarnings("unchecked")
		@RequestMapping(value = "/toDetail", method = { RequestMethod.POST,
				RequestMethod.GET })
		public ModelAndView toDetail(HttpServletRequest request,
				HttpServletResponse response,Model m,UserInfo userInfo) throws Exception {
			
			ModelAndView modelAndView = new ModelAndView();
			
			if (userInfo != null && StringUtils.isNotBlank(userInfo.getUserPid())) {
				UserInfo entity = userInfoService.selectByPrimaryKey(userInfo);
				
				
				if (entity != null) {
					
					m.addAttribute("flag","detail");
					m.addAttribute("userInfo",entity);
					
					PersonInfo personInfo = null;
					List<PersonInfo> personInfoList = personInfoService.query(personInfo);
					m.addAttribute("personInfoList",personInfoList);
					
					modelAndView.setViewName("user/user_info_crud");
					return modelAndView;
				} else {
					return null;
				}
			}
			return null;

		}
}
